import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/home.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

class SMSLoginPage extends StatefulWidget {
  static const String routeName = '/login/sms';

  @override
  _SMSLoginPageState createState() => _SMSLoginPageState();
}

class _SMSLoginPageState extends State<SMSLoginPage> {
  TextEditingController _controller = TextEditingController();

  String _phoneNum;
  var _countdownTime = 0;
  Timer _timer;

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _timer?.cancel();
  }

  @override
  void initState() {
    super.initState();
    _startCountdown();
  }

  @override
  Widget build(BuildContext context) {
    _phoneNum = ModalRoute.of(context).settings.arguments as String;
    return Scaffold(
      appBar: AppBar(elevation: 0),
      body: ListView(
        padding: EdgeInsets.only(left: 30, right: 30, top: 30),
        children: [
          Text(
            "请输入验证码",
            style: TextStyle(
              color: Colors.black87,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, bottom: 50),
            child: Text(
              '验证码已发送至：${_phoneNum.substring(0, 3)}****${_phoneNum.substring(7, 11)}',
              style: TextStyle(color: Colors.grey[700]),
            ),
          ),
          TextField(
            keyboardType: TextInputType.number,
            controller: _controller,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(4),
            ],
            decoration: InputDecoration(
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.grey[300]),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.grey[300]),
              ),
              hintText: '输入4位数字验证码',
              suffixIcon: _countdownTime == 0
                  ? TextButton(
                      onPressed: _getCode,
                      child: Text(
                        '获取验证码',
                        style: TextStyle(color: Theme.of(context).primaryColor),
                      ),
                    )
                  : Container(
                      width: 40,
                      alignment: Alignment.centerRight,
                      child: Text(
                        '$_countdownTime' + 's',
                        style: TextStyle(color: Theme.of(context).primaryColor),
                      ),
                    ),
            ),
          ),
          PrimaryButton(
            '登录',
            margin: EdgeInsets.symmetric(vertical: 60),
            onPressed: _login,
          )
        ],
      ),
    );
  }

  /// 开始倒计时
  void _startCountdown() {
    _countdownTime = 60;
    final call = (timer) {
      setState(() {
        _countdownTime -= 1;
        if (_countdownTime == 0) {
          _timer?.cancel();
        }
      });
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  void _login() async {
    CommonUtils.hideKeyboard(context);
    DialogUtils.showWaitDialog(context);
    try {
      var data = await XHttp.postJson(Urls.SMS_LOGIN, {
        "verificationCode": _controller.text.trim(),
        "cellphone": _phoneNum
      });
      if (data != null) {
        MapResponse response =
            MapResponse.fromJson(data as Map<String, dynamic>);
        if (response.code == 200) {
          User user = User.fromJson(response.data);
          context.read<StoreInfo>().updateUser(user);
          // 登录成功，判断是否有IM账号，没有的话直接注册。
          await CommonUtils.loginIM(context, _phoneNum);
          Navigator.popUntil(context, ModalRoute.withName(HomePage.routeName));
        } else {
          Navigator.pop(context);
          ToastUtil.show(response.msg, context);
        }
      } else {
        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
      Navigator.pop(context);
    }
  }

  void _getCode() async {
    CommonUtils.hideKeyboard(context);
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postFormData(
        Urls.GET_VERIFICATION_CODE, {"phoneNumber": _phoneNum});
    Navigator.pop(context);
    if (data != null) {
      Map<String, dynamic> response = data as Map<String, dynamic>;
      if (response['code'] == 1) {
        _startCountdown();
      } else {
        ToastUtil.show(response['msg'], context);
      }
    }
  }
}
